package com.zhanglinwei.openApiServer.generate;

import com.zhanglinwei.common.utils.AssertUT;
import com.zhanglinwei.openApiClient.segment.SelectSegment;
import com.zhanglinwei.openApiClient.segment.WhereSegment;
import com.zhanglinwei.openApiClient.utils.ClassUtils;
import com.zhanglinwei.openApiClient.utils.SQLHelper;
import com.zhanglinwei.openApiClient.wrapper.AbstractLambdaWrapper;
import com.zhanglinwei.openApiServer.utils.SQLVerifyUtils;

import java.lang.reflect.Field;

public class SQLGenerator {

    private SQLGenerator(){}

    public static String ofLambdaWrapper(AbstractLambdaWrapper<?, ?> lambdaWrapper) {
        if (lambdaWrapper == null) {
            return "";
        }

        String entityClassFullPath = lambdaWrapper.getEntityClassFullPath();
        WhereSegment whereSegment = lambdaWrapper.getWhereSegment();
        SelectSegment selectSegment = lambdaWrapper.getSelectSegment();

        Class<?> entityClass = ClassUtils.loadClass(entityClassFullPath);
        AssertUT.notNull(entityClass, "The entity is not allowed to operate");

        Field[] declaredFields = entityClass.getDeclaredFields();

        AssertUT.isTrue(SQLVerifyUtils.simpleLegalEntity(entityClassFullPath), "The entity is not allowed to operate");
        AssertUT.isTrue(SQLVerifyUtils.verifyColumn(declaredFields, whereSegment.columns()), "There are columns that are not allowed to operate");
        AssertUT.isTrue(SQLVerifyUtils.verifyColumn(declaredFields, selectSegment.columns()), "There are columns that are not allowed to operate");
        AssertUT.isTrue(SQLVerifyUtils.verifySqlInject(selectSegment.alias()), "The alias has sql injection");
//        AssertUT.isTrue(SQLVerifyUtils.verifyFunction(new ArrayList<>()), "The alias has sql injection");

        return SQLHelper.wrapperToSQL(lambdaWrapper, false);
    }

}
